package com.newland.esp.controller.user;

import com.google.code.kaptcha.Producer;
import com.newland.esp.common.constant.RedisKeyConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @param
 * @author lw
 * @descripe 生成图形验证码
 * @date 2021/8/16 16:45
 * @Version 1.0
 **/
@Controller
@CrossOrigin
@RequestMapping("/image")
public class KaptchaControlle {

    @Autowired
    private Producer producer;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @RequestMapping("/getKaptchaImage")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws  IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String capText = producer.createText();
        System.out.println("验证码:" + capText);
        // 将验证码存入redis
        redisTemplate.opsForValue().set(RedisKeyConstant.USER_VERIFICATION,capText,2, TimeUnit.MINUTES);
        //生成图片验证码
        BufferedImage image = producer.createImage(capText);

        ServletOutputStream out = response.getOutputStream();

        ImageIO.write(image, "jpg", out);
    }
}
